package com.cjk.console.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cjk.console.mqtt.MqttSubscribeClient;
import com.cjk.console.tunnel.TunnelInit;
import com.cjk.foundation.dao.QuartzJobDao;
import com.cjk.foundation.entity.QuartzJobEntity;
import com.cjk.foundation.enums.IsStatus;
import com.cjk.foundation.job.JobManager;

public class InitListener implements ServletContextListener {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(InitListener.class);

	@SuppressWarnings("unchecked")
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		JobManager jobManager = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(JobManager.class);
		QuartzJobDao quartzJobDao = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(QuartzJobDao.class);
		List<QuartzJobEntity> quartzJobEntities = quartzJobDao.selectListByCondition(IsStatus.TRUE);
		for(QuartzJobEntity job : quartzJobEntities){
			try {
				jobManager.addJob((Class<? extends Job>)(Class.forName(job.getClassName()).newInstance().getClass()), job.getName(), job.getGroupName(), job.getCron());
				LOGGER.info("注入job：{}", job.getName());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 开启mqtt订阅服务
		new MqttSubscribeClient();
		// 初始化隧道配置
		new TunnelInit();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

}
